package com.blockmeta.bbs.immodule.activity;

import android.content.Intent;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.blankj.utilcode.util.LogUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.activity.chat.UCGChatActivity;
import com.blockmeta.bbs.immodule.adapter.SelectMemberAdapter;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.bean.beaninterface.IFriendsEntry;
import com.blockmeta.bbs.immodule.bean.sort.PinyinComparator;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.net.api.CreateCircleApi;
import com.blockmeta.bbs.immodule.net.api.GetWatchApi;
import com.blockmeta.bbs.immodule.net.pojo.CircleDetailResponse;
import com.blockmeta.bbs.immodule.net.pojo.Fans;
import com.blockmeta.bbs.immodule.net.pojo.IMUserEntityBook;
import com.blockmeta.bbs.immodule.utils.HanziToPinyin;
import com.blockmeta.bbs.immodule.widget.SideBar;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author airthor
 * @date 2019/3/14
 * 创建圈子选择成员
 */
public class CreateGroupSelectMemberActivity extends BaseActivity implements SideBar.OnTouchingLetterChangedListener {
    @BindView(R2.id.rcv_friends)
    RecyclerView mRcvFriends;
    @BindView(R2.id.group_dialog)
    TextView mGroupDialog;
    @BindView(R2.id.sidebar)
    SideBar mSidebar;

    ToggleButton mFans_selector;


    private List<IFriendsEntry> mFriendsEntries = new ArrayList<>();
    private List<Fans> mFanEntries = new ArrayList<>();
    public SelectMemberAdapter mMemberAdapter;

    private HashMap<String, String> params;

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        return getLayoutInflater().inflate(R.layout.activity_create_group_select_member, null);
    }

    @Override
    protected void initialize() {
        super.initialize();
        Intent intent = getIntent();

        if (intent != null) {
            params = (HashMap<String, String>) intent.getSerializableExtra("params");
        }
        mSidebar.setOnTouchingLetterChangedListener(this);
        mSidebar.bringToFront();
        mSidebar.setTextView(mGroupDialog);

        View header = getLayoutInflater().inflate(R.layout.header_fans_for_create_group, null);
        mFans_selector = header.findViewById(R.id.tg_fans_selector);
        header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFans_selector.setChecked(!mFans_selector.isChecked());
            }
        });
        mRcvFriends.setLayoutManager(new LinearLayoutManager(this));
        mMemberAdapter = new SelectMemberAdapter(R.layout.item_contacts_friends, mFriendsEntries);
        mMemberAdapter.addHeaderView(header);
        mMemberAdapter.bindToRecyclerView(mRcvFriends);
        mMemberAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                LogUtils.d("tingim", "onItemClick");
                IFriendsEntry item = (IFriendsEntry) adapter.getItem(position);
                item.setCheckedState(!item.getCheckedState());
                ToggleButton toggleButton = (ToggleButton) view.findViewById(R.id.tg_selector);
                toggleButton.setChecked(item.getCheckedState());
            }
        });

        netWork();
    }

    private void netWork() {
        List<IMUserEntity> friends = IMApplicationContext.getUserDomainService().getBookListFriends(AccountHelper.getUidInt());
        for (IMUserEntity friend : friends) {
            IMUserEntityBook friendsBook = new IMUserEntityBook();
            friendsBook.setLetter(HanziToPinyin.getInstance().getLetter(friend.getName()));
            friendsBook.setName(friend.getName());
            friendsBook.setUserId(friend.getUserId());
            friendsBook.setAvatarPath(friend.getAvatarPath());
            friendsBook.setIsFriend(friend.getIsFriend());
            friendsBook.setDate(friend.getDate());
            friendsBook.setUserLevel(friend.getUserLevel());
            mFriendsEntries.add(friendsBook);
        }
        Collections.sort(mFriendsEntries, new PinyinComparator());
        mMemberAdapter.notifyDataSetChanged();

        //获取粉丝
        RetrofitFactory.getRetrofit().create(GetWatchApi.class)
                .getWatch(AccountHelper.getUidInt())
                .compose(this.<BaseImResponse<List<Fans>>>bindToLifecycle())
                .compose(RxUtil.<List<Fans>>commonResult())
                .compose(RxUtil.<List<Fans>>rxSchedulerHelper())
                .subscribe(new CommonSubscriber<List<Fans>>(mContext) {
                    @Override
                    public void onNext(List<Fans> list) {
                        mFanEntries.addAll(list);
                    }
                });
    }

    @Override
    public void onTouchingLetterChanged(String s) {
        mMemberAdapter.scrollToTargetLetter(s);
    }


    @OnClick({R2.id.fl_back, R2.id.fl_next})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.fl_back) {
            finish();

        } else if (i == R.id.fl_next) {
            createCircle();

        } else {
        }
    }

    private void createCircle() {
        ProgressBarUtil.showProgress(mContext);
        putSelectMemberIntoParam();

        RetrofitFactory.getRetrofit().create(CreateCircleApi.class)
                .createCircle(params)
                .compose(RxUtil.<BaseImResponse<CircleDetailResponse>>rxSchedulerHelper())
                .compose(RxUtil.<CircleDetailResponse>commonResult())
                .compose(this.<CircleDetailResponse>bindToLifecycle())
                .subscribe(new CommonSubscriber<CircleDetailResponse>(mContext) {
                    @Override
                    public void onNext(CircleDetailResponse circleDetailResponse) {
                        //上一个界面关闭
                        CreateGroupInfoActivity.Instance.finish();
                        circleDetailResponse.isMeIn = true;
                        IMApplicationContext.getCircleDomainService().saveImUserEntityByCircleResponse(circleDetailResponse);
                        //暂时跳转圈子聊天页面
                        Intent intent = new Intent(mContext, UCGChatActivity.class);
                        intent.putExtra(Params.USER_TAG, (long) circleDetailResponse.id);
                        mContext.startActivity(intent);
                        //关闭此页面
                        finish();
                    }
                });
    }

    private void putSelectMemberIntoParam() {
        StringBuilder ids = new StringBuilder();
        Set<Long> userIds = new HashSet<>();
        //添加选中的好友,如果勾选了粉丝，要把粉丝也全部加入进来
        for (IFriendsEntry friendsEntry : mFriendsEntries) {
            if (friendsEntry.getCheckedState()) {
                userIds.add(friendsEntry.getUserId());
            }
        }
        if(mFans_selector.isChecked()) {
            for (Fans fans : mFanEntries) {
                userIds.add(fans.fansId);
            }
        }
        for(Long userId : userIds){
            ids.append(userId).append("_");
        }
        if (ids.length()!=0){
            String inviteId = ids.substring(0,ids.length()-1);
            params.put("users",inviteId);
        }
    }
}
